﻿Imports System.ComponentModel

Public Module Threading

	Dim Threads As New List(Of BackgroundWorker)

	Delegate Sub AsyncMethod(ByVal Obj As Object)

	Class ThreadInfo
		Public MethodToRun As AsyncMethod
		Public CallBack As AsyncMethod
		Public Parameter As Object
		Public Thread As BackgroundWorker
	End Class

	Sub AsyncRun(ByVal MethodToRun As AsyncMethod, ByVal Callback As AsyncMethod, ByVal Obj As Object)
		Dim Thread As New BackgroundWorker
		Dim Info As New ThreadInfo
		Info.Thread = Thread
		Info.MethodToRun = MethodToRun
		Info.CallBack = Callback
		Info.Parameter = Obj
		Threads.Add(Thread)
		AddHandler Thread.DoWork, AddressOf ThreadBody
		AddHandler Thread.RunWorkerCompleted, AddressOf ThreadDone
		Thread.RunWorkerAsync(Info)
	End Sub

	Sub ThreadBody(ByVal sender As Object, ByVal e As DoWorkEventArgs)
		Dim Info As ThreadInfo = e.Argument
		Info.MethodToRun(Info.Parameter)
		e.Result = Info
	End Sub

	Sub ThreadDone(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
		Dim Info As ThreadInfo = e.Result
		Info.CallBack(Info.Parameter)
		Threads.Remove(Info.Thread)
	End Sub

End Module